//
//  DLBaseTextField+ScrollText.m
//  DGGBaseSDK
//
//  Created by dgg_hzk on 2018/4/26.
//  Copyright © 2018年 dgg. All rights reserved.
//

#import "DLBaseTextField+ScrollText.h"
#import <objc/runtime.h>

static NSString * const enableScrollKey = @"enableScrollKey";
static NSString * const textScrollDirectionKey = @"textScrollDirectionKey";
static NSString * const scrollXKey = @"scrollXKey";
static NSString * const textWidthKey = @"textWidthKey";
static NSString * const leftToRightKey = @"leftToRightKey";
static NSString * const isMovingKey = @"isMovingKey";
static NSString * const scrollTimerKey = @"scrollTimerKey";

@implementation DLBaseTextField (ScrollText)

- (void)setIsMoveing:(BOOL)isMoveing{
    objc_setAssociatedObject(self, &isMovingKey, @(isMoveing), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (BOOL)isMoveing{
    NSNumber *isMoveingValue = objc_getAssociatedObject(self, &isMovingKey);
    if (!isMoveingValue) {
        objc_setAssociatedObject(self, &isMovingKey, @(NO), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        isMoveingValue = objc_getAssociatedObject(self, &isMovingKey);
    }
    return [isMoveingValue boolValue];
}

- (void)setLeftToRight:(BOOL)leftToRight{
    objc_setAssociatedObject(self, &leftToRightKey, @(leftToRight), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (BOOL)leftToRight{
    NSNumber *leftToRightValue = objc_getAssociatedObject(self, &leftToRightKey);
    if (!leftToRightValue) {
        objc_setAssociatedObject(self, &leftToRightKey, @(NO), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        leftToRightValue = objc_getAssociatedObject(self, &leftToRightKey);
    }
    return [leftToRightValue boolValue];
}

- (void)setTextWidth:(CGFloat)textWidth{
    objc_setAssociatedObject(self, &textWidthKey, @(textWidth), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (CGFloat)textWidth{
    NSNumber *textWidthValue = objc_getAssociatedObject(self, &textWidthKey);
    if (!textWidthValue) {
        objc_setAssociatedObject(self, &textWidthKey, @(0.0), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        textWidthValue = objc_getAssociatedObject(self, &textWidthKey);
    }
    return [textWidthValue floatValue];
}

- (void)setScrollX:(CGFloat)scrollX{
    objc_setAssociatedObject(self, &scrollXKey, @(scrollX), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (CGFloat)scrollX{
    NSNumber *scrollXValue = objc_getAssociatedObject(self, &scrollXKey);
    if (!scrollXValue) {
        objc_setAssociatedObject(self, &scrollXKey, @(0.0), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        scrollXValue = objc_getAssociatedObject(self, &scrollXKey);
    }
    return [scrollXValue floatValue];
}

- (void)setEnableScroll:(BOOL)enableScroll{
    objc_setAssociatedObject(self, &enableScrollKey, @(enableScroll), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    if(enableScroll){
        [self addTarget:self action:@selector(textFieldDidBeginEditingAction:) forControlEvents:UIControlEventEditingDidBegin];
        [self addTarget:self action:@selector(textFieldDidEndEditingAction:) forControlEvents:UIControlEventEditingDidEnd];
        self.textWidth = [self.text sizeWithAttributes:@{NSFontAttributeName:self.font}].width;
        if(self.textWidth > self.bounds.size.width && !self.isEditing && self.enableScroll){
            [self startMoving];
        }
    }
}

- (BOOL)enableScroll{
    NSNumber *isEnableScroll = objc_getAssociatedObject(self, &enableScrollKey);
    if (!isEnableScroll) {
        objc_setAssociatedObject(self, &enableScrollKey, @(NO), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        isEnableScroll = objc_getAssociatedObject(self, &enableScrollKey);
    }
    return [isEnableScroll boolValue];
}

- (void)setTextScrollDirection:(TextFieldScrollDirection)textScrollDirection{
    objc_setAssociatedObject(self, &textScrollDirectionKey, @(textScrollDirection), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (TextFieldScrollDirection)textScrollDirection{
    NSNumber *scrollDirection = objc_getAssociatedObject(self, &textScrollDirectionKey);
    if (!scrollDirection) {
        objc_setAssociatedObject(self, &textScrollDirectionKey, @(0), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        scrollDirection = objc_getAssociatedObject(self, &textScrollDirectionKey);
    }
    return [scrollDirection intValue];
}

- (void)setText:(NSString *)text{
    [super setText:text];
    self.textWidth = [text sizeWithAttributes:@{NSFontAttributeName:self.font}].width;
    if(self.textWidth > self.bounds.size.width && !self.isEditing && self.enableScroll){
        [self startMoving];
    }
}

#pragma mark - 监听编辑状态
- (void)textFieldDidBeginEditingAction:(DLBaseTextField *)sender{
    [self stopMoving];
}

- (void)textFieldDidEndEditingAction:(DLBaseTextField *)sender{
    self.textWidth = [sender.text sizeWithAttributes:@{NSFontAttributeName:self.font}].width;
    self.scrollX = 0;//编辑完成，滚动X轴归0
    if(self.textWidth > self.bounds.size.width && self.enableScroll){
        [self startMoving];
    }
}

- (CGRect)textRectForBounds:(CGRect)bounds{
    CGRect TextFieldRect = [super textRectForBounds:bounds];
    if(self.enableScroll){
        switch (self.textScrollDirection) {
            case TextFieldScrollAbout:{
                //左右来回滚动
                if (self.textWidth > TextFieldRect.size.width) {
                    if (self.scrollX >= self.textWidth - (TextFieldRect.size.width - (bounds.size.width - TextFieldRect.size.width) * 0.5)) {
                        self.leftToRight = YES;
                    } else if (self.scrollX <= 0.0f) {
                        self.leftToRight = NO;
                    }
                    if (!self.leftToRight) {
                        self.scrollX += 0.5f;
                    } else {
                        self.scrollX -= 0.5f;
                    }
                    TextFieldRect.origin.x -= self.scrollX;
                    TextFieldRect.size.width = self.textWidth;
                }
            }break;
            case TextFieldScrollToLeft:{
                //向左滚动
                if (self.textWidth > TextFieldRect.size.width) {
                    if (self.scrollX >= self.textWidth - (TextFieldRect.size.width - (bounds.size.width - TextFieldRect.size.width) * 0.5) + self.frame.size.width) {
                        self.leftToRight = NO;
                        self.scrollX = -self.frame.size.width;
                    }else if (self.scrollX <= -(self.textWidth - bounds.size.width)){
                        
                    }
                    self.scrollX += 0.5f;
                    TextFieldRect.origin.x -= self.scrollX;
                    TextFieldRect.size.width = self.textWidth;
                }
            }break;
            case TextFieldScrollToRight:{
                //向右滚动
                if (self.textWidth > TextFieldRect.size.width) {
                    if (self.scrollX <= 0.0f - self.bounds.size.width) {
                        self.leftToRight = NO;
                        self.scrollX = self.textWidth;
                    }
                    self.scrollX -= 0.5f;
                    TextFieldRect.origin.x -= self.scrollX;
                    TextFieldRect.size.width = self.textWidth;
                }
            }break;
            default:break;
        }
        return TextFieldRect;
    }else{
        return TextFieldRect;
    }
}

- (void)startMoving {
    if (!self.isMoveing) {
        self.isMoveing = YES;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self moveTextField];
        });
    }
}

- (void)stopMoving {
    NSLog(@"____停止滚动");
    if (self.isMoveing) {
        self.isMoveing = NO;
    }
    //收回所有延迟执行请求
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(moveTextField) object:nil];
}

- (void)moveTextField {
    if (!self.isMoveing) {
        return;
    }
    if ([self.text length] > 0) {
        [self setNeedsLayout];
    }
    //延迟执行
    [self performSelector:@selector(moveTextField) withObject:nil afterDelay:1.0 / 30.0]; // 30 FPS
}

@end
